package com.zycfc.zsf.boot.web.wrapper;

import javax.servlet.http.*;
import java.nio.charset.*;
import org.apache.commons.lang3.*;
import org.springframework.util.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import org.slf4j.*;

public class RequestWrapper extends HttpServletRequestWrapper
{
    private static final Logger log;
    private final byte[] body;
    
    public RequestWrapper(final HttpServletRequest request) {
        super(request);
        final String sessionStream = this.getBodyString((ServletRequest)request);
        this.body = sessionStream.getBytes(StandardCharsets.UTF_8);
    }
    
    public String getBodyString(final ServletRequest request) {
        final String contentType = request.getContentType();
        StringBuilder bodyString = new StringBuilder();
        if (StringUtils.isNotBlank((CharSequence)contentType) && (contentType.contains("multipart/form-data") || contentType.contains("x-www-form-urlencoded"))) {
            final Enumeration<String> pars = (Enumeration<String>)request.getParameterNames();
            while (pars.hasMoreElements()) {
                final String n = pars.nextElement();
                bodyString.append(n).append("=").append(request.getParameter(n)).append("&");
            }
            bodyString = new StringBuilder(bodyString.toString().endsWith("&") ? bodyString.substring(0, bodyString.length() - 1) : bodyString.toString());
            return bodyString.toString();
        }
        try {
            final byte[] byteArray = StreamUtils.copyToByteArray((InputStream)request.getInputStream());
            bodyString = new StringBuilder(new String(byteArray, StandardCharsets.UTF_8));
        }
        catch (IOException e) {
            RequestWrapper.log.error(e.getMessage());
        }
        return bodyString.toString();
    }
    
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader((InputStream)this.getInputStream()));
    }
    
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bais = new ByteArrayInputStream(this.body);
        return new ServletInputStream() {
            public int read() {
                return bais.read();
            }
            
            public boolean isFinished() {
                return false;
            }
            
            public boolean isReady() {
                return false;
            }
            
            public void setReadListener(final ReadListener readListener) {
            }
        };
    }
    
    static {
        log = LoggerFactory.getLogger((Class)RequestWrapper.class);
    }
}
